Before speaking about the keywords var,let and const, I believe it is extremely important to understand the concept of scope.
Variables declared outside any function (globally) have global scope
Here, the variable global can be accessed from anywhere.
Variables declared inside a function (locally) have local scope
Here, the variable local can be accessed only inside the function.
Some variables can be accessed only block i.e.,within {}
Here , the variable block can be accessed only within the if block. It cannot be accessed from anywhere else. Thus, the variable block has only block scope.
Now that we are clear with the scope, let's dive into the var,let and const keywords.
The variables defined with the keyword var have function scope.If it is defined outside the function , then the scope of the variable is global.
Here, the variable foo defined with the keyword var can be accessed from anywhere while the variable bar is limited to the function scope.
The variables declared with the keyword var can be redeclared and reassigned.
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
Variables declared with var keyword are hoisted at the top of its scope and is initialized with undefined.
Here, the variable foo is declared later.But it is hoisted at the top and initialized to undefined.
Only variables declared with var keyword exhibit this behaviour.
In the above example, since the variable a is not declared with var keyword, it is not hoisted and hence trying to access the variable before declaration in the hoist function throws an error.
The variables declared with the keyword let have block scope.
Here, the variable i can be accessed only within the for loop.
Variables declared with let keyword cannot be redeclared, but it can be reassigned.
Variables declared with let are also hoisted at the top, but let variables are not initialized until their definition is evaluated.This is because of Temporal Dead Zone.
Thus,trying to access the variable foo before declaration gives reference error.
The variables declared with the keyword const also have block scope.
Variables declared with const keyword must be initialized at the time of its declaration itself.Otherwise an error is thrown.
Variables declared with const keyword cannot be redeclared and reassigned.
Attempting to overwrite objects with const keyword throws error. But object keys are not protected and they are mutable.
Here, we can see that the object cannot be reassigned, but the keys of the object are mutable.
Similarly arrays declared with const keyword cannot be overwritten. But the elements in the array is mutable.
Variables declared with const keyword behave the same way as
var | let | const | |
---|---|---|---|
Scope | Function or Global | Block | Block |
Redeclare | Yes | No | No |
Reassign | Yes | Yes | No |
Hoisted | Yes | No | No |